<?php

namespace app\api\controller;

use app\api\model\Config;
use app\api\model\Posts;
use app\api\model\Postsaux;
use app\api\model\Users;
use app\api\model\BonusUsers;
use app\api\model\Pickup;
use app\api\model\Order as OrderModel;
use app\api\model\OrderGoods;
use app\api\model\UsersMoneylog;

require_once VENDOR_PATH.'Wxpay/lib/WxPay.Api.php';
require_once VENDOR_PATH.'Wxpay/example/WxPay.JsApiPay.php';

class Order extends Api
{
    protected $noNeedLogin = ['order_payUrl'];
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    //确认订单
    public function confirm(){
        $posts_id = input('id',''); //套餐ID
        $aux = input('aux','');     //附加项
        $num = input('num',1);      //订餐数
        $pickup_id = input('pickup_id',''); //提货点ID
        $time = input('time','');       //取餐时间
        //参数验证
        $pickup = $this->order_check($posts_id,$pickup_id,$time);
        $posts = Posts::where(['id'=>$posts_id,'status'=>'1','del'=>0])->field("id,name,date,image,price,content")->find();
        if(empty($posts)){
            return_msg(1,'该套餐已下架！');
        }
        $endtime = Config::getValue(['name'=>'endtime'],'value');//下单结束时间
        if(time() > strtotime($posts['date'].' '.$endtime)){
            //当天订餐时间已过
            return_msg(1,'当天订餐时间已过,无法订餐哦');
        }
        $auxList = [];
        if(!empty($aux)){
            $auxList = json_decode($aux,true);
        }
        
        $postsList = [];
        $moneys = 0;
        $auxids = [];
        for($i=0;$i<$num;$i++){
            $moneys += $posts['price'];
            $posts_aux = isset($auxList[$i])?$auxList[$i]:[];
            $posts_auxList = [];
            if(!empty($posts_aux)){
                $posts_aux_ids = array_column($posts_aux,'id');
                $auxids[] = $posts_aux_ids;
                //查询附加项
                $posts_auxList = Postsaux::where(['id'=>['in',$posts_aux_ids]])->field("id,name,price")->select();
                $posts_auxList = collection($posts_auxList)->toArray();
                foreach($posts_auxList as $v2){
                    $moneys += $v2['price'];
                }
            }
            $data = [
                'posts' =>  [
                    'id'        =>      $posts['id'],
                    'name'      =>      $posts['name'],
                    'price'     =>      $posts['price']
                ],
                'posts_aux' =>  $posts_auxList
            ];
            $postsList[] = $data;
        }
        //查询可用优惠券
        $where = [
            'bu.users_id'   =>  $this->userInfo['id'],
            'bu.endtime'    =>  ['>=',time()]
        ];
        $field = "bu.id,bu.num,bu.ynum,bu.endtime,b.name,b.postsaux_id,b.type,b.bonus_money";
        $bonus = BonusUsers::getList($where,$field,1,999);
        $bonusList = [];
        if(!empty($bonus['list'])){
            //查询附加项
            $postsaux = Postsaux::column('price','id');
            foreach($bonus['list'] as $key=>$val){
                if($val['num'] <= 0){
                    continue;
                }
                if($val['type'] == 1){
                    //满减券
                    if($moneys >= $val['money']){
                        $bonusList[] = $val;
                    }
                }else{
                    //计算可抵扣金额
                    $val['bonus_money'] = isset($postsaux[$val['postsaux_id']])?$postsaux[$val['postsaux_id']]:0;
                    $bonusList[] = $val;
                }
            }
        }

        $return = [
            'users_money'   =>      $this->userInfo['money'],//用户余额
            'posts_id'      =>      $posts_id,  //套餐ID
            'num'           =>      $num,       //购买数量
            'aux'           =>      $aux,       //所选附加项
            'pickup'        =>      $pickup,    //取餐点信息
            'time'          =>      $time,      //取餐时间
            'moneys'        =>      strval($moneys),    //总金额
            'posts_list'    =>      $postsList, //套餐信息
            'bonus_list'    =>      $bonusList  //优惠券信息
        ];
        return_msg(0,'查询成功',$return);
    }

    //提交订单(自提)
    public function addorder(){
        $posts_id = input('id',''); //套餐ID
        $aux = input('aux','');     //附加项
        $num = input('num',1);      //订餐数
        $pickup_id = input('pickup_id',''); //提货点ID
        $time = input('time','');       //取餐时间
        $bonus_id  = input('bonus_id',0);   //优惠券ID
        $pay_type  = input('pay_type',1);   //支付方式:1=微信支付,2=余额支付

        //参数验证
        $pickup = $this->order_check($posts_id,$pickup_id,$time);
        $posts = Posts::where(['id'=>$posts_id,'status'=>'1','del'=>0])->field("id,name,date,image,price,content")->find();
        if(empty($posts)){
            return_msg(1,'该套餐已下架！');
        }
        $endtime = Config::getValue(['name'=>'endtime'],'value');//下单结束时间
        if(time() > strtotime($posts['date'].' '.$endtime)){
            //当天订餐时间已过
            return_msg(1,'当天订餐时间已过,无法订餐哦');
        }
        $auxList = [];
        if(!empty($aux)){
            $auxList = json_decode($aux,true);
        }
        $postsList = [];
        $moneys = $auxmoneys = 0;
        for($i=0;$i<$num;$i++){
            $moneys += $posts['price'];
            $posts_aux = isset($auxList[$i])?$auxList[$i]:[];
            $posts_auxList = [];
            $aux_money = 0;
            if(!empty($posts_aux)){
                $posts_aux_ids = array_column($posts_aux,'id');
                //查询附加项
                $posts_auxList = Postsaux::where(['id'=>['in',$posts_aux_ids]])->field("id,name,price")->select();
                $posts_auxList = collection($posts_auxList)->toArray();
                foreach($posts_auxList as $v2){
                    $moneys += $v2['price'];
                    $aux_money += $v2['price'];
                    $auxmoneys += $v2['price'];
                }
            }
            $data = [
                'posts_id'      =>  $posts['id'],
                'posts_price'   =>  $posts['price'],
                'name'          =>  $posts['name'],
                'aux'           =>  json_encode($posts_auxList),
                'aux_money'     =>  $aux_money,
                'image'         =>  $posts['image'],
            ];
            $postsList[] = $data;
        }
        //查询优惠金额
        $bonus_money = 0;
        if(!empty($bonus_id)){
            $bonus_field = "bu.id,bu.num,bu.ynum,bu.endtime,b.name,b.postsaux_id,b.type,b.bonus_money";
            $bonus = BonusUsers::getInfo(['bu.id'=>$bonus_id,'bu.users_id'=>$this->userInfo['id']],$bonus_field);
            if(empty($bonus)){
                return_msg(1,'该优惠券暂不可用！');
            }
            if($bonus['endtime'] < time()){
                return_msg(1,'该优惠券已过期,无法使用！');
            }
            if($bonus['num'] <= 0){
                return_msg(1,'该优惠券已用完,无法使用！');
            }
            if($bonus['type'] == 1){
                //满减券
                if($moneys >= $bonus['money']){
                    $bonus_money = $bonus['bonus_money'];
                }else{
                    return_msg(1,'该优惠券需满'.$bonus['money'].'元才能使用！');
                }
            }else{
                //计算可抵扣金额
                $bonus_money = Postsaux::where(['id'=>$bonus['postsaux_id']])->value('price');
            }
        }
        $orders = [
            'order_sn'      =>      get_trade_no(),
            'users_id'      =>      $this->userInfo['id'],
            'date'          =>      $posts['date'],
            'money'         =>      bcsub($moneys,$bonus_money,2),
            'posts_id'      =>      $posts_id,
            'num'           =>      $num,
            'aux'           =>      json_encode($auxList),
            'pickup_id'     =>      $pickup_id,
            'time'          =>      $time,
            'bonus_id'      =>      $bonus_id,
            'bonus'         =>      $bonus_money,
            'posts_money'   =>      $posts['price'],
            'aux_money'     =>      $auxmoneys,
            'type'          =>      '1',
            'pickup_name'   =>      $pickup['name'],
            'address'       =>      $pickup['address'],
            'lat'           =>      $pickup['lat'],
            'lng'           =>      $pickup['lng'],
            'contacts'      =>      $pickup['contacts'],
            'phone'         =>      $pickup['phone'],
            'addtime'       =>      time(),
            'posts_name'    =>      $posts['name'],
            'posts_image'   =>      $posts['image'],
            'pay_type'      =>      strval($pay_type),
            'endtime'       =>      strtotime($posts['date'].' '.$time)
        ];
       
        if($pay_type == 2){
            //余额支付
            if($this->userInfo['money'] < $orders['money']){
                return_msg(1,'您的余额不足,请选择其他支付方式！');
            }
        }
        $order_id = OrderModel::insertGetId($orders);
        foreach($postsList as &$val){
            $val['order_id'] = $order_id;
        }
        OrderGoods::insertAll($postsList);
        //更新优惠券
        if(!empty($bonus_id)){
            BonusUsers::where(['id'=>$bonus_id])->setInc('ynum',1);
        }
        if($pay_type == 1){
            //拉起支付
            $input = new \WxPayUnifiedOrder();
            $input->SetBody('订餐');
            $input->SetAttach('订餐');
            $input->SetOut_trade_no($orders['order_sn']);
            $input->SetTotal_fee($orders['money']*100);
            $input->SetTime_start(date("YmdHis"));
            $input->SetTime_expire(date("YmdHis", time() + 600));
            $payReturn = 'http://'.$_SERVER['HTTP_HOST'].url('Order/order_payUrl');
            $input->SetOpenid($this->userInfo['openid']);
            $input->SetNotify_url($payReturn);
            $input->SetTrade_type("JSAPI");
            $order = \WxPayApi::unifiedOrder($input);
            if($order['return_msg']=="OK"){
                $tools = new \JsApiPay();
                $jsApiParameters = $tools->GetJsApiParameters($order);
                $jsApiParameters['mch_id'] = $order['mch_id'];
                $jsApiParameters['prepay_id'] = $order['prepay_id'];
                return_msg(0,'微信支付调用成功',['order_id'=>$order_id,'money'=>strval($orders['money']),'pat_status'=>0,'pay'=>$jsApiParameters]);
            }else{
                return_msg(1,'微信支付调用失败');
            }
        }else{
            //余额支付  扣除余额,更改订单状态
            Users::where(['id'=>$this->userInfo['id']])->setDec('money',$orders['money']);
            //生成余额记录
            $log = [
                'users_id'      =>      $this->userInfo['id'],
                'money'         =>      -$orders['money'],
                'type'          =>      2,
                'date'          =>      date("Y-m-d"),
                'addtime'       =>      time(),
                'desc'          =>      $posts['name'],
                'order_id'      =>      $order_id
            ];
            UsersMoneylog::insert($log);
            OrderModel::where(['id'=>$order_id])->update(['order_status'=>'1','pay_time'=>time()]);
            return_msg(0,'余额支付成功',['order_id'=>$order_id,'money'=>strval($orders['money']),'pat_status'=>1]);
        }

    }

    //支付回调
    public function order_payUrl()
    {
        controller('Notify')->Handle(false);
    }

    //订单验证
    public function order_check($posts_id,$pickup_id,$time){
        if(empty($posts_id)){
            return_msg(1,'参数错误：请传入套餐ID！');
        }
        if(empty($pickup_id)){
            return_msg(1,'请选择取餐点！');
        }
        if(empty($time)){
            return_msg(1,'请选择取餐时间！');
        }
        $pickup = Pickup::where(['id'=>$pickup_id,'del'=>0])->field('id,name,address,lat,lng,contacts,phone,status,desc')->find();
        if(empty($pickup)){
            return_msg(1,'该取餐点不存在,请选择其他取餐点！');
        }
        if($pickup['status'] == 2){
            return_msg(1,$pickup['desc']);
        }
        return $pickup;
    }

    //订单列表
    public function order_list(){
        //默认进行中
        $type = input('type',1);//1=进行中,2=历史订单
        $page = input('page',1);
        $limit = input('limit',10);
        $where['users_id'] = $this->userInfo['id'];
        if($type == 1){
            //进行中
            $where['order_status'] = '1';
        }else{
            $where['order_status'] = ['not in',[0,1]];
        }
        $date = input('date','');
        if(!empty($date)){
            $start_time = strtotime($date);
            $end_time = strtotime($date.' 23:59:59');
            $where['addtime'] = ['between',[$start_time,$end_time]];
        }
        $field = "id,order_sn,order_status,money,num,time,pickup_id,pickup_name,address,lat,lng,contacts,phone,posts_name,posts_image,addtime,is_invoice,is_refund";
        $return = OrderModel::getList($where,$field,$page,$limit);
        $kfname = Config::getValue(['name'=>'kfname']);
        $kfphone = Config::getValue(['name'=>'kfphone']);
        $tcphone = Config::getValue(['name'=>'tcphone']);
        return_msg(0,'查询成功',['kfname'=>$kfname,'kfphone'=>$kfphone,'tcphone'=>$tcphone,'total'=>$return['total'],'page'=>$page,'list'=>$return['list']]);
    }

    //订单详情
    public function order_info(){
        $id = input('id',0);    //订单ID
        $field = "id,order_sn,order_status,money,time,pickup_id,pickup_name,address,lat,lng,contacts,phone,bonus,bonus_id,bonus,addtime";
        $order = OrderModel::where(['id'=>$id,'users_id'=>$this->userInfo['id']])->field($field)->find();
        if(empty($order)){
            return_msg(1,'参数错误：订单不存在！');
        }
        $goodsList = OrderGoods::where(['order_id'=>$id])->field('posts_id,name,posts_price,aux,aux_money')->select();
        $goods_moneys = 0;
        foreach($goodsList as $v){
            $goods_moneys += $v['posts_price'];
            $goods_moneys += $v['aux_money'];
            $v['aux'] = json_decode($v['aux'],true);
        }
        $bonus = [];
        if(!empty($order['bonus_id'])){
            $bonus_field = "bu.id,b.name,b.type,b.bonus_money";
            $bonus = BonusUsers::getInfo(['bu.id'=>$order['bonus_id']],$bonus_field);
        }
        $order['addtime'] = date("Y-m-d H:i:s",$order['addtime']);
        $order['bonus_info'] = $bonus;
        $order['goods_amount'] = strval($goods_moneys);
        $order['order_goods'] = $goodsList;
        return_msg(0,'查询成功',$order);
    }
}